import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios';
import Cookies from 'js-cookie';

Vue.config.productionTip = false
Vue.use(ElementUI);

// 添加请求拦截器
axios.interceptors.request.use(
    (config) => {
        const token = Cookies.get('token'); // 从 Cookie 中获取 token
        console.log(`从 Cookie 中获取 token为：${token}`);
        if (token) {
            config.headers['Authorization'] = `${token}`; // 设置请求头
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 添加响应拦截器
axios.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response && error.response.status === 401) {
            Cookies.remove('token'); // 清除无效 token
            alert('登录状态已过期，请重新登录');
            window.location.href = '/login'; // 重定向到登录页
        }
        return Promise.reject(error);
    }
);

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
